package com.hjm.project.report.report.service.impl;

import com.google.common.collect.Maps;
import com.hjm.project.report.report.mapper.ReportMerchantMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Map;
import java.util.Set;

/**
 * @author puyiliang
 * @date create in 2021/1/16 19:10
 */
@Component
public class ReportMerchantTask {

    @Autowired
    private ReportMerchantMapper reportMerchantMapper;


    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void insertBankInfo(Map<String, Set<String>> terminalMap, Map<String, String> data, String source, String loginName) throws Exception{

        int result = 0;
        Set<String> terminalSet = terminalMap.get(data.get("bno"));
        if (ObjectUtils.isEmpty(terminalSet)){
            throw new Exception("不存在对应终端");
        }
        //新增bankInfo
        if ("1".equals(source)){
            result = reportMerchantMapper.mergeInsertTBankInfo(data);
        }else if("2".equals(source)){
            result = reportMerchantMapper.insertTBankInfo(data);
        }
        if (result <= 0){
            throw new Exception("商编添加失败");
        }
        int index = 0;
        //新增bankKey(t_bankterno)
        for (String terminalNo : terminalSet) {
            index++;
            Map<String, String> terminal = Maps.newHashMap();
            terminal.put("bid", data.get("bid"));
            terminal.put("terminalId", terminalNo);
            terminal.put("createMan", loginName);
            terminal.put("index", String.valueOf(index));
            result = reportMerchantMapper.insertBankTerNo(terminal);
        }
        if (result <= 0){
            throw new Exception("银行终端密匙记录添加失败");
        }
        //新增bank_deal_index
        Map<String, String> dealIndex = Maps.newHashMap();
        dealIndex.put("bid", data.get("bid"));
        dealIndex.put("index", String.valueOf(index));
        result = reportMerchantMapper.insertBankDealIndex(dealIndex);
        if (result <= 0){
            throw new Exception("索引记录添加失败");
        }
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public int saveEditBankInfo(Map<String, String> data) {
        return reportMerchantMapper.saveEditBankInfo(data);
    }
}
